/*
 * CodeSaveCommand.java
 *
 * Created on 2006년 3월 29일 (수), 오후 4:11
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.qbooks.app;

import java.util.*;





import javax.servlet.*;
import javax.servlet.http.*;

import org.json.simple.JSONObject;

import com.zll.framework.model.HashBox;
import com.zll.framework.model.HashList;
import com.zll.framework.servlet.Command;
import com.zll.framework.util.StringUtil;
import com.qbooks.app.AppDAO;
import com.qbooks.common.CommonUtil;





/**
 *
 * @author eastar
 */
public class DownloadBookCommand implements Command
{
	private final String D = "\"";

    public String execute(HttpServletRequest  request, HttpServletResponse response)
    throws Exception
    {
    	String os	= (String)request.getAttribute("os");


    	String bookCode	= StringUtil.nvl(request.getParameter("book_code"));
    	String id		= StringUtil.nvl(request.getParameter("id"));
    	String mac		= StringUtil.nvl(request.getParameter("mac"));

    	AppDAO dao 		= new AppDAO();
    	int result_code = 100;


    	HashMap infos 	= new HashMap();
    	infos.put("book_code", bookCode);
    	infos.put("member_id", id);
    	infos.put("mac", mac);
    	infos.put("os_type", os);

    	//파라미터 체크
    	if ("".equals(id)) {
    		result_code = 201;
    	}
    	else if ("".equals(mac)) {
    		result_code = 205;
    	}
    	else {
	    	//mac 등록 체크
			HashList list 	= dao.selectMemberBook(infos);
	    	if (list.size() == 1) 
	    	{
				if (list.getInt("sales_count", 0) == 0) {
					result_code = 304;	//구매하지 않은 책
				}
				else if (list.getInt("mac_count",0) == 0) {	
		    		result_code = 307;	//등록되지 않은 mac
		    	}
				else if ("".equals(list.get("book_path",0))) {
					result_code = 302;	//존재하지 않는 책
				}
				else {
					request.setAttribute("file_dir", list.get("book_path",0));	//성공
				}
				
			} else {
				result_code = 302;	//존재하지 않는 책
			}
    	}

    	System.out.println(">>>>>>>>>>result_code:"+ result_code);

		if (result_code == 100) {
			infos.put("download_type", "1"); 	//유료
			dao.insertBookDownload(infos);
			return "/common/download_view.jsp";
		}
		else {

			if ("android".equals(os)) {
				JSONObject json = new JSONObject();

				json.put("if_code", "DNB");
				json.put("result_code", result_code);

				request.setAttribute("jsonData", json.toString());
			}
			else if ("ios".equals(os)) {
				request.setAttribute("jsonData", "{\"status\", \""+result_code+"\"}");
			}

			return "/common/json_view.jsp";
		}

    }
}
